package com.enlorenz.support.jackson;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.SerializerProvider;

/**
 * 基础的Json序列化工具
 * @author Karma
 */
public class BaseJsonSerializer extends JsonSerializer<Object>{
	private List<IDataTransfer> transferList
	=new ArrayList<IDataTransfer>();
	
	public void addTransfer(IDataTransfer dataTransfer){
		transferList.add(dataTransfer);
	}
	
	@Override
	public void serialize(Object value, JsonGenerator jgen,
			SerializerProvider provider) throws IOException,
			JsonProcessingException {
		if(null == value){
			return;
		}
		
		for(IDataTransfer trans:transferList){
			if(trans.isAdpat(value)){
				Object res=trans.transfer(value);
				jgen.writeObject(res);
				return;
			}
		}
		
		if(value instanceof String){
			jgen.writeString((String)value);
		}else{
			jgen.writeObject(value);
		}
	}

	public List<IDataTransfer> getTransferList() {
		return transferList;
	}

	public void setTransferList(List<IDataTransfer> transferList) {
		this.transferList = transferList;
	}
}
